package priv.tuyou.redis.lock;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class MyLock {

    private Jedis jedis;
    private String lock;
    private int timeout = 10;
    private String value = UUID.randomUUID().toString();

    public MyLock(Jedis jedis, String lock) {
        this.jedis = jedis;
        this.lock = lock;
    }

    public void lock() {
        while (true) {
            if (jedis.setnx(lock, value) == 1) {
                jedis.expire(lock, timeout);
                return;
            }
            try {
                TimeUnit.MICROSECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void unlock() {
        //只有自己才能删除
        if (value.equals(jedis.get(lock))) {
            jedis.del(lock);
        }
    }

    public static int countdown = 100;

    public static void main(String[] args) {
        try (JedisPool pool = new JedisPool("localhost", 6379)) {

            IntStream.rangeClosed(1, 100).parallel().forEach(i -> {
                System.out.println("开始：" + i);

                try (Jedis jedis = pool.getResource()) {
                    MyLock lock = new MyLock(jedis, "countdown");
                    lock.lock();
                    try {
                        countdown--;
                        System.out.println(countdown);
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }
        System.out.println("结束");
    }
}
